<template>
  <view class="weachat-circle-container">
    <view class="weachat-circle-input-content">
      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/word.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">朋友圈文案</view>
        </view>
        <view class="title-tips">*文案字数最多500字/非必填</view>
      </view>

      <!-- content -->
      <view class="circle-content">
        <view style="height: 100%;width: 100%;overflow-y: auto">
          <textarea
            v-model="circle"
            placeholder="请填写/粘贴您的文案（非必填）"
            placeholder-style="fontSize:24rpx"
            :auto-height="false"
            maxlength="500"
            class="circle-input" />
        </view>
        <view class="word-length">{{ circle.length }}/500</view>
      </view>

      <!-- title -->
      <view class="w-title flex jb ac">
        <view class="title-content flex">
          <image
            src="/static/icon/photo.png"
            mode="scaleToFill"
            class="word-icon"
          />
          <view class="title-text">上传图片</view>
        </view>
        <view class="title-tips">*最多9张图，至少1张图,长按拖动排序</view>
      </view>

      <!-- upload photo -->
      <view class="upload-photo-content">
        <ImageList
          v-model="list"
          keyName="cover_url"
          :cols="3"
          :borderRadius="16"
          :number="9"
          :upload-config-props="uploadConfig">
        </ImageList>
      </view>

      <!-- upload btn -->
      <!-- 上传按钮确定 -->
      <view class="confirm-btn">
        <u-button
          class="btn"
          type="primary"
          shape="circle"
          hover-class="none"
          :custom-style="{
            backgroundColor: '#56d39d',
            fontWeight: 700
          }"
          @click="sumbitArtworks"
          :disabled="uploadNumConfig.surplus <= 0"
          :loading="btnLoading">上传素材</u-button>
      </view>

      <!-- 保护隐私协议 -->
      <view class="agreement flex ac jc">
        <u-checkbox-group active-color="#56d39d" class="flex ac jc">
          <u-checkbox v-model="agreement" size="40"></u-checkbox><text @click="handleAgreement">同意《用户服务协议》及《隐私政策》</text>
        </u-checkbox-group>
      </view>
      
    </view>

    <!-- 海报 -->
    <lPainter
      :board="posterObj"
      ref="painter"
      @success="createPosterSuccess"
      :is-render-image="true"></lPainter>
  </view>
</template>

<script>
  import { getAliyunCosSignature, artworksInfoById } from '@/api/applet';
  import { checkText } from '@/utils/index';
  import { userTextTemplateArtworksCreate } from '@/api/artworks';
  import ImageList from './components/imageList.vue';
  import { checkMaxUploadMax } from '@/api/artworks';
  import lPainter from '@/components/limePainter/index.vue';
  import { mapGetters } from 'vuex';
  import config from '@/utils/config';
  export default {
    components: {
      ImageList,
      lPainter
    },
    data() {
      return {
        circle: '',
        list: [],
        uploadConfig: null,
        uploadNumConfig: {
          max_upload_num: 0,
          surplus: 0,
          todayUploadNum: 0
        },
        btnLoading: false,
        agreement: true,
        posterObj: {
					width: '680rpx',
					height: '1188rpx',
					background: '#fff',
					borderRadius: '16rpx',
					views: []
				},
        imageBase64: '',
        uploadAction: `${config.baseApi}/client/upload/aliyunUpload`,
        author_id: '',
        id: ''
      }
    },
    computed: {
      ...mapGetters([
        'userInfo',
        'token'
      ])
    },
    watch: {
      list: {
        handler(val) {
          console.log(val)
        }
      }
    },
    onLoad(options) {
      this.author_id = options.author_id;
      this.id = options.id || '';
      if (options.id) {
        this.getArtworksInfoById();
      }
      this.getCheckMaxUploadMax();
      this.getAliyunCosSignature();
    },
    methods: {

      // 获取作品信息
      getArtworksInfoById() {
        artworksInfoById({
          id: this.id
        }).then(result => {
          if (result && result.data) {
            let data = result.data;
            this.circle = data.wechat_content || '';
            this.list = data.font_attribute;
          }
        });
      },

      // 获取阿里云配置
      getAliyunCosSignature() {
        getAliyunCosSignature({
          dir: 'wechatcircle'
        }).then(result => {
          if (result && result.data) {
            this.uploadConfig = result.data;
          }
        });
      },

      // 生成封面
      async createPosterSuccess(imageBase64) {
        let file = await this.dataURLtoFile(imageBase64, `${this.userInfo.id}-${new Date().getTime()}`);
        this.uploadImage(file);
      },

      // 上传图片
      async uploadImage(file) {
        uni.showLoading({
          title: '上传中',
          mask: true
        })
        const that = this;
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: that.uploadAction,
            name: 'file',
            file,
            header: {
              'Authorization': 'Bearer ' + that.token // token
            },
            formData: {
              dir: 'wechatcircle'
            },
            success: (res) => {
              let result_ = res && res.data ? JSON.parse(res.data) : null;
              if (result_) {
                // 创建文字模板
                userTextTemplateArtworksCreate({
                  id: that.id,
                  author_id: that.author_id,
                  cate_id: '',
                  album_id: '',
                  type: 11,
                  font_attribute: that.list,
                  cover_url: result_.data.cover_path,
                  wx_cover_url: result_.data.cover_path,
                  wechat_content: that.circle || '朋友圈素材',
                  audit_status: 'review'
                }).then(result => {
                  if (result.code == 200) {
                    uni.showToast({
                      title: '提交成功',
                      icon: 'none'
                    })
                    setTimeout(function() {
                      let pages = getCurrentPages();
                      let pagesLength = pages.length;

                      if (pagesLength > 1) {
                        uni.navigateBack({
                          delta: 1,
                        })
                      } else {
                        uni.switchTab({ url: '/pages/creativeCenter/index' });
                      }
                    }, 2000)
                  }
                })
              }
            },
            fail: function (e) {
              uni.hideLoading();
              console.log(e);
            }
          })
        });
      },

      // 检查当天上传作品的次数
      getCheckMaxUploadMax() {
        checkMaxUploadMax().then(result => {
          if (result && result.data) {
            this.uploadNumConfig = result.data;
          }
        })
      },

      // 确定提交
      async sumbitArtworks() {
        if (!this.agreement) {
          uni.showToast({
            title: '请勾选同意《用户服务协议》及《隐私政策》，在提交',
            icon: 'none',
            mask: false,
          })
          return;
        }

        if (this.list && this.list.length === 0) {
          uni.showToast({
            title: '请上传图片素材',
            icon: 'none',
            mask: false,
          })
          return;
        }

        // 检查文本内容
        const flag = await checkText(this.circle || '朋友圈素材');
        if (flag) {
          this.btnLoading = true;
          // 设置封面
          this.createPoster();
        }
      },

      // 创建封面
      createPoster() {
        let imageList = this.list;
        let posterItem = [{
          type: 'image',
          src: 'https://img.alicdn.com/imgextra/i2/1888948409/O1CN01YdZypK2BzNRMq7plA_!!1888948409.png',
          css: {
            left: '0',
            top: '0',
            width: '680rpx',
            height: '1188rpx',
            borderRadius: '0'
          }
        }, {
          type: 'text',
          text: this.circle || '朋友圈素材',
          maxLines: 3,
          css: {
            left: '24rpx',
            top: '330rpx',
            width: '644rpx',
            height: '128rpx',
            fontSize: '28rpx',
            color:'#333333',
            lineHeight: '42rpx',
            fontWeight: 'bold'
          }
        }];

        let imageIndex = 0;
        let top = 490;
        let left = 24;
        imageList.forEach((item, index) => {
          let i = index + 1;
          left = 24 + (200 * imageIndex) + (16 * imageIndex);
          posterItem.push({
            type: 'image',
            src: item.cover_url,
            mode: 'aspectFill',
            css: {
              left: `${left}rpx`,
              top: `${top}rpx`,
              width: '200rpx',
              height: '200rpx'
            }
          });
          imageIndex = imageIndex + 1;
          if (i === 3) {
            imageIndex = 0;
            left = 24;
            top = 490 + 200 + 16;
          } else if (i === 6) {
            imageIndex = 0;
            left = 24;
            top = 490 + 400 + 32;
          }
        });

      
        this.posterObj.views = posterItem;
      },

      // 转成file对象
			async dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				let fileType = mime.split('/');
				return new File([u8arr], `${filename}${fileType.length > 1 ? '.' + fileType[1] : ''}`, { type: mime });
			},

      // 前往同意
      handleAgreement() {
        uni.navigateTo({ url: '/pages/about/agreement' })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .weachat-circle-container{
    padding: 24rpx 0;

    .w-title{
      margin-bottom: 24rpx;
      padding: 0 24rpx;
    }

    .title-content{
      .word-icon{
        width: 40rpx;
        height: 40rpx;
      }

      .title-text{
        font-size: 30rpx;
        font-weight: bold;
        margin-left: 8rpx;
      }
    }

    .title-tips{
      font-size: 22rpx;
      color: #666;
    }

    .circle-content{
      margin: 0 auto;
      width: calc(100% - 48rpx);
      height: 290rpx;
      background: #fafafc;
      border: 2rpx solid #eee;
      border-radius: 10rpx;
      padding: 30rpx 30rpx 68rpx;
      position: relative;
      margin-bottom: 32rpx;

      .circle-input{
        font-size: 24rpx;
        width: 100%;
      }

      .word-length{
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 24rpx;
        text-align: right;
        font-size: 26rpx;
        color: #67676a;
        line-height: 36rpx;
        padding-right: 30rpx;
      }
    }

    .upload-photo-content{
      margin-bottom: 32rpx;
    }

    .confirm-btn{
      padding: 24rpx;
    }

    .create-album{
      position: absolute;
      right: 0;
      top: 0;
      margin: auto;
      font-size: 26rpx;
      font-weight: 400;
      color: $uni-color-primary;
      background: #f3f7fb;
      padding: 6rpx 24rpx;
      border-radius: 24rpx;
    }

    .agreement{
      margin-top: 24rpx;
      font-size: 24rpx;
    }
  }
</style>
